package io.github.jesse205.transferstation.lite;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.ArrayList;

import io.github.jesse205.transferstation.lite.activities.DialogActivity;
import io.github.jesse205.transferstation.lite.services.DragDropService;
import io.github.jesse205.transferstation.lite.sources.AppSource;

public class DragDropApplication extends android.app.Application implements ServiceConnection {

    private static final String TAG = "DADTSApplication";
    private final ArrayList<Runnable> postWhenAppServiceStartedList = new ArrayList<>();
    private SharedPreferences defaultSharedPreferences;
    @Nullable
    private DragDropService.DragAndDropServiceBinder appService;
    private boolean isAppServiceStarted = false;
    private AppSource appSource;

    private int defaultPanelX;
    private int defaultPanelY;


    @Override
    public void onCreate() {
        super.onCreate();
        defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        // dragAndDropChangeSupport = new PropertyChangeSupport(this);
        appSource = new AppSource();
        defaultPanelX = getResources().getDimensionPixelSize(R.dimen.root_x_default);
        defaultPanelY = getResources().getDimensionPixelSize(R.dimen.root_y_default);
        setAppServiceStarted(isAppEnabled());
    }

    public int getPanelX() {
        return defaultSharedPreferences.getInt(DragDropPreferences.KEY_POSITION_X, defaultPanelX);
    }

    public int getPanelY() {
        return defaultSharedPreferences.getInt(DragDropPreferences.KEY_POSITION_Y, defaultPanelY);
    }

    public void setPanelPosition(int x, int y) {
        defaultSharedPreferences.edit()
                .putInt(DragDropPreferences.KEY_POSITION_X, x)
                .putInt(DragDropPreferences.KEY_POSITION_Y, y)
                .apply();
    }

    public boolean isAppEnabled() {
        return defaultSharedPreferences.getBoolean(DragDropPreferences.KEY_ENABLE_APP, false);
    }

    public void setAppEnabled(boolean enabled) {
        defaultSharedPreferences.edit().putBoolean(DragDropPreferences.KEY_ENABLE_APP, enabled).apply();
        setAppServiceStarted(enabled);
    }

    public boolean isAdsorb() {
        return defaultSharedPreferences.getBoolean(DragDropPreferences.KEY_ADSORB, true);
    }

    public void setAdsorb(boolean adsorb) {
        if (appService != null) appService.setAdsorb(adsorb);
    }

    public boolean isDropPageEnabled() {
        return defaultSharedPreferences.getBoolean(DragDropPreferences.KEY_ENABLE_DROP_PAGE, false);
    }

    public void postWhenAppServiceStarted(Runnable runnable) {
        if (appService != null)
            runnable.run();
        else
            postWhenAppServiceStartedList.add(runnable);
    }

    public void setAppServiceStarted(boolean started) {
        if (isAppServiceStarted != started) isAppServiceStarted = started;
        else return;
        Intent intent = new Intent(this, DragDropService.class);
        if (started) {
            // startService(intent);
            if (!Settings.canDrawOverlays(this)) {
                Intent dialogIntent = new Intent(this, DialogActivity.class);
                dialogIntent.putExtra("title", android.R.string.dialog_alert_title);
                dialogIntent.putExtra("message", R.string.permission_ask_drawOverlays);
                dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
                this.startActivity(dialogIntent);
                return;
            }
                /* new AlertDialog.Builder(this)
                        .setTitle(R.string.permission_ask)
                        .setMessage(R.string.permission_ask_drawOverlays)
                        .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                            this.startActivity(PermissionsHelper.getIntentToOverlaySettingActivity(this));
                        })
                        .setNegativeButton(android.R.string.no, null)
                        .show(); */
                // throw new SecurityException("application cannot draw overlays.");
            bindService(intent, this, BIND_AUTO_CREATE);
        } else {
            // stopService(intent);
            unbindService(this);
            // 因为解绑不会有回调，所以需要单独判断
            if (appService != null) {
                // appService.getClipDataSource().setData(null);
                appService.getPanelChangeSource().setState(false);
            }
            appService = null;
            appSource.setState(started);

        }
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        appService = (DragDropService.DragAndDropServiceBinder) service;
        appService.setAdsorb(isAdsorb());
        appService.checkAndStartBridgeActivity();
        appSource.setState(true);
        Log.d(TAG, "onServiceConnected: ");
        for (Runnable runnable : postWhenAppServiceStartedList) {
            postWhenAppServiceStartedList.remove(runnable);
            runnable.run();
        }

    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        setAppEnabled(false);
        Log.d(TAG, "onServiceDisconnected: ");
    }

    public void restartAppService() {
        if (isAppServiceStarted) {
            setAppServiceStarted(false);
            setAppServiceStarted(true);
        }
    }

    // public PropertyChangeSupport getPanelChangeSupport() {
    //     return appService.getPanelChangeSupport();
    // }

    /* public PropertyChangeSupport getDragAndDropChangeSupport() {
        return dragAndDropChangeSupport;
    } */

    @Nullable
    public DragDropService.DragAndDropServiceBinder getAppService() {
        return appService;
    }

    public AppSource getAppSource() {
        return appSource;
    }
}
